package movie6.posprintercept2.extensions

import android.content.ContentResolver
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.preference.PreferenceManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import movie6.posprintrecept2.module.CINEMA_ID
import movie6.posprintrecept2.module.DEVICE_SEC
import movie6.posprintrecept2.module.USER_TOKEN
import movie6.posprintrecept2.module.pref_key_device_id
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


//存储key对应的数据
fun Context.SharedPreferencesSave2String(key: String, info: String): Unit {
    // 1.获得SharedPreferences对象
    var sp: SharedPreferences = getSharedPreferences(key, MODE_PRIVATE)
    // 2.获得Editor对象
    var et: SharedPreferences.Editor = sp.edit()
    // 3.存储数据
    et.putString(key, info)
    // 4.提价
    et.commit()


}

fun <T> ArrayList<T>.splitList(threshold: Int):List<List<T>>{
    var result = ArrayList<List<T>>()

    var subPage = this.size / threshold
    if(this.size % threshold != 0) subPage += 1


    for(i in 0 until subPage){
        if(subPage == 1) {
            result.addAll(listOf(this!!.subList(i * threshold, this.size)))
        } else {
            when (i) {
                0 -> result.addAll(listOf(this!!.subList(0, ((i + 1) * threshold))))
                subPage - 1 -> result.addAll(listOf(this!!.subList(i * threshold, this!!.size)))
                else -> result.addAll(listOf(this!!.subList(i * threshold, ((i + 1) * threshold))))
            }
        }

    }
    return result
}

fun String.formatServerDate(newFormat:String):String{
     var newStr = this.replace("T","-").replace("Z","")
     var oldFromat = SimpleDateFormat("yyyy-MM-dd-HH:mm:sss")
     var date = oldFromat.parse(newStr)
     var newFormat = SimpleDateFormat(newFormat)
    return newFormat.format(date)

}

//取key对应的数据
fun Context.SharedPreferencesGet2String(key: String): String {
    // 1.获得SharedPreferences对象
    var sp: SharedPreferences = getSharedPreferences(key, MODE_PRIVATE )
    // 2.取数据
    var result: String? = sp.getString(key, "")
    return result ?: ""

}

fun Context.saveToken( token:String){
    var sp: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    sp.edit().putString(USER_TOKEN,token).apply()


}

fun Context.saveSec(deviceId: String){
    var sp: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    sp.edit().putString(DEVICE_SEC,deviceId).apply()
}

fun Context.getDeviceSec():String{
    var sp: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    var result: String? = sp.getString(DEVICE_SEC, "")
    return result ?: ""

}


fun Context.getToken():String{
    var sp: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    var result: String? = sp.getString(USER_TOKEN, "")
    return result ?: ""

}

fun Context.saveCinemaId( token:String){
    var sp: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    sp.edit().putString(CINEMA_ID,token).apply()


}

fun <T>Context.saveList(key: String,datas:List<T>){

}

fun View.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()
fun View.dip(value: Float): Int = (value * resources.displayMetrics.density).toInt()


fun View.sp(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt()
fun View.sp(value: Float): Int = (value * resources.displayMetrics.scaledDensity).toInt()

fun View.removeParentView(): View {
    (parent as? ViewGroup)?.removeView(this)
    return this
}

fun View.setBackgroundColorWithDefault(color: String?, default: Int) {
    try {
        if(color?.isEmpty() == true){
            setBackgroundColor(default)
        } else {
            setBackgroundColor(Color.parseColor(color))
        }
    } catch (e: Exception) {
        setBackgroundColor(default)
    }
}

fun Context.getCinemaId():String{
    var sp: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
    var result: String? = sp.getString(CINEMA_ID, "")
    return result ?: ""

}


fun Calendar.getNdayAfter(date:Int):Date{
    this.add(Calendar.DATE, date)
    return this.time
}

fun Calendar.getNdayBefore(date:Int):Date{

    this.add(Calendar.DATE, -date)
    return this.time
}




fun Context.getResourcesUri(@DrawableRes id:Int):String {
    var  resources = this.getResources();
    var uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
            resources.getResourcePackageName(id) + "/" +
            resources.getResourceTypeName(id) + "/" +
            resources.getResourceEntryName(id);
    return uriPath;
}


/**
 * kotlin extensions start axOctivity
 */
fun <T> Context.openActivity(it: Class<T>, extras: Bundle.() -> Unit = {}) {
    var intent = Intent(this, it)
    intent.putExtras(Bundle().apply(extras))
    startActivity(intent)
}

fun Context.sendErrorBrocast(extras: String){
    var intent = Intent()
    intent.putExtra("extra",extras)
    sendBroadcast(intent)
}

fun TextView.textWatcher(watcher: KtxTextWatcher.() -> Unit) =
    addTextChangedListener(KtxTextWatcher().apply(watcher))

class KtxTextWatcher : TextWatcher {

    private var _afterTextChanged: ((Editable?) -> Unit)? = null
    private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
    private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null


    fun afterTextChanged(listener: ((Editable?) -> Unit)) {
        _afterTextChanged = listener
    }

    fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
        _beforeTextChanged = listener
    }

    fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
        _onTextChanged = listener
    }

    override fun afterTextChanged(s: Editable?) {
        _afterTextChanged?.invoke(s)
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        _beforeTextChanged?.invoke(s, start, count, after)
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        _onTextChanged?.invoke(s, start, before, count)
    }

}

inline fun <reified T : Any> Gson.fromJson(json: String): T {
    return fromJson(json, object : TypeToken<T>() {}.type)
}


inline fun Context.longToast(message: Int) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()

inline fun Context.longToast(message: String) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()



inline val Context.defaultSharedPreferences: SharedPreferences
    get() = PreferenceManager.getDefaultSharedPreferences(this)